from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
import datetime
import re

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于flash消息

# 初始化数据库
def init_db():
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    
    # 创建日记表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS diary_entries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
    ''')
    
    conn.commit()
    conn.close()

# 获取所有日记条目
def get_all_entries():
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, title, content, created_at, updated_at FROM diary_entries ORDER BY created_at DESC')
    entries = cursor.fetchall()
    conn.close()
    return entries

# 搜索日记条目
def search_entries(query):
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    
    # 搜索标题或内容中包含查询词的条目，或者日期匹配
    cursor.execute('''
        SELECT id, title, content, created_at, updated_at FROM diary_entries 
        WHERE title LIKE ? OR content LIKE ? OR created_at LIKE ?
        ORDER BY created_at DESC
    ''', (f'%{query}%', f'%{query}%', f'%{query}%'))
    
    entries = cursor.fetchall()
    conn.close()
    return entries

# 获取单个日记条目
def get_entry_by_id(entry_id):
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, title, content, created_at, updated_at FROM diary_entries WHERE id = ?', (entry_id,))
    entry = cursor.fetchone()
    conn.close()
    return entry

# 添加新日记条目
def add_entry(title, content):
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO diary_entries (title, content, created_at, updated_at) VALUES (?, ?, ?, ?)', 
                  (title, content, now, now))
    conn.commit()
    conn.close()

# 更新日记条目
def update_entry(entry_id, title, content):
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE diary_entries SET title = ?, content = ?, updated_at = ? WHERE id = ?', 
                  (title, content, now, entry_id))
    conn.commit()
    conn.close()

# 删除日记条目
def delete_entry(entry_id):
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    cursor.execute('DELETE FROM diary_entries WHERE id = ?', (entry_id,))
    conn.commit()
    conn.close()

# 简单的文本分析 - 统计字数
def count_words(text):
    words = re.findall(r'\b\w+\b', text)
    return len(words)

# 获取日记统计信息
def get_diary_stats():
    conn = sqlite3.connect('diary.db')
    cursor = conn.cursor()
    
    # 计算总条目数
    cursor.execute('SELECT COUNT(*) FROM diary_entries')
    total_entries = cursor.fetchone()[0]
    
    # 获取最早和最新的日记日期
    cursor.execute('SELECT MIN(created_at), MAX(created_at) FROM diary_entries')
    date_range = cursor.fetchone()
    
    # 计算平均每条日记的字数
    cursor.execute('SELECT content FROM diary_entries')
    contents = cursor.fetchall()
    total_words = sum([count_words(content[0]) for content in contents])
    avg_words = round(total_words / total_entries) if total_entries > 0 else 0
    
    conn.close()
    
    return {
        'total_entries': total_entries,
        'date_range': date_range,
        'avg_words': avg_words
    }

# 主页路由\@app.route('/')
def index():
    search_query = request.args.get('search', '')
    
    if search_query:
        entries = search_entries(search_query)
        flash(f'搜索结果: "{search_query}"')
    else:
        entries = get_all_entries()
    
    stats = get_diary_stats()
    return render_template('index.html', entries=entries, search_query=search_query, stats=stats)

# 新建日记路由\@app.route('/new', methods=['GET', 'POST'])
def new_entry():
    if request.method == 'POST':
        title = request.form['title'].strip()
        content = request.form['content'].strip()
        
        if not title or not content:
            flash('标题和内容不能为空！')
            return redirect(url_for('new_entry'))
        
        add_entry(title, content)
        flash('日记创建成功！')
        return redirect(url_for('index'))
    
    return render_template('edit.html', entry=None, action='new')

# 编辑日记路由\@app.route('/edit/<int:entry_id>', methods=['GET', 'POST'])
def edit_entry(entry_id):
    entry = get_entry_by_id(entry_id)
    
    if not entry:
        flash('日记不存在！')
        return redirect(url_for('index'))
    
    if request.method == 'POST':
        title = request.form['title'].strip()
        content = request.form['content'].strip()
        
        if not title or not content:
            flash('标题和内容不能为空！')
            return redirect(url_for('edit_entry', entry_id=entry_id))
        
        update_entry(entry_id, title, content)
        flash('日记更新成功！')
        return redirect(url_for('index'))
    
    return render_template('edit.html', entry=entry, action='edit')

# 删除日记路由\@app.route('/delete/<int:entry_id>')
def delete_entry_route(entry_id):
    entry = get_entry_by_id(entry_id)
    
    if not entry:
        flash('日记不存在！')
    else:
        delete_entry(entry_id)
        flash('日记删除成功！')
    
    return redirect(url_for('index'))

# 启动时初始化数据库
if __name__ == '__main__':
    init_db()
    print('个人日记应用已启动！访问 http://localhost:5000 开始使用。')
    app.run(debug=True)